/********************************************************************
 * Copyright(c) 2023-2023 Grayson Zheng.
 * File: uart.C
 * Description: AT89C52 serial communication program, the default
 * crystal oscillator frequency is 11.0592MHz.
 * Version: 1.0
 * Date: 2023-07-20
 * Author: zhengxinyu13@qq.com
 * ---------- Revision History ----------
 * <version>
 * <date>
 * <author>
 * <desc>
 * Modified to be suitable to the new coding rules in all functions.
 ********************************************************************/
 
#include "uart.h"

REC UART_rec={0};

void uart_init(uint_16 baudrate)
{
#if (PARITYBIT == NONE_PARITY)
	SCON = 0x50;		//8-bit variable UART.
#elif (PARITYBIT == ODD_PARITY) || (PARITYBIT == EVEN_PARITY) || (PARITYBIT == MARK_PARITY)
	SCON = 0xDA;		//9-bit variable UART, parity bit initial to 1,
#elif (PARITYBIT == SPACE_PARITY)
	SCON = 0xD2;		//9-bit variable UART, parity bit initial to 0.
#endif

	TMOD &= 0x0F;
	TMOD |= 0x20;		//Set Timer1 as 8-bit auto reload mode.

	TH1 = TL1 = -(FOSC_1/_12T_MODEL/SYSCLK/baudrate);	//Set auto-reload vaule.

	TR1 = TURN_ON;		//Timer1 start run.
	ES  = TURN_ON;		//Enable UART interrupt.
	EA  = TURN_ON;		//Open master interrupt switch.
}

/*----------------------------
 * Send a byte data to UART
 * Input: data to be sent
 * Output:None
----------------------------*/
void send_byte(int_8 data_msg)
{
    SBUF = data_msg;	//Send data to UART buffer
    while (!TI);
    RESET_BIT(TI);
}

/*-----------------------------
 * Send a string to UART
 * Input: address of string
 * Output:None
-----------------------------*/
void send_msg(int_8 *data_msg)
{
    while (*data_msg)				//Check the end of the string
        send_byte(*data_msg++);		//Send current char and increment string ptr
}

void uart_isr(void) interrupt 4
{
	uint_8 temp = 0;

	if (RI)
		RESET_BIT(RI);	//Clear receive interrupt flag

	temp = SBUF;

	if (temp == 0 || temp == '\n' || UART_rec.len >= 64 || temp == END_MARK) {
		UART_rec.buff[UART_rec.len] = '\0';
		UART_rec.flag = TURN_ON;
		UART_rec.len = 0;
	} else {
		UART_rec.buff[UART_rec.len++] = temp;
	}

	if (UART_rec.flag) {
		send_msg("Received successfully!\r\n");
		send_msg(UART_rec.buff);
		send_msg("\r\n");
		UART_rec.flag = TURN_OFF;
	}
}
